<template>
    <div class="forPass">
         <span><h4> 修改密码</h4></span>
         <el-form label-position="left" label-width="75px" :model="resetForm" status-icon :rules="rules" ref="resetForm"  >

        <el-form-item label="新密码:" prop="newPass">
          <el-input v-model="resetForm.newPass" show-password prefix-icon="el-icon-lock" class="login-subject-input" type="password"
            placeholder="请输入新密码"></el-input>
        </el-form-item>

        <el-form-item label="确认密码:" prop="renewPass">
          <el-input v-model="resetForm.renewPass" show-password prefix-icon="el-icon-lock" class="login-subject-input"  type="password"
            placeholder="请确认新密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUserPassword('resetForm')">修改</el-button>
      </span>
    </div>
</template>
<script>
import { editUserp } from '@/api/user'
export default {
  name: 'changepass',
  data () {
    var validatePass = (rule, value, callback) => {
      const passReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/
      if (!value) {
        return callback(new Error('新密码不能为空'))
      }
      setTimeout(() => {
        if (passReg.test(value)) {
          callback()
        } else {
          callback(new Error('密码至少包含 数字和英文，长度6-20'))
        }
      }, 100)
    }
    var validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('新密码不能为空'))
      } else if (value !== this.resetForm.newPass) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      // 重置密码
      resetForm: {
        newPass: '',
        renewPass: ''
      },
      rules: {
        newPass: [
          {
            require: true, validator: validatePass, trigger: 'blur'
          }
        ],
        renewPass: [
          {
            require: true, validator: validatePass2, trigger: 'blur'
          }
        ]

      }
    }
  },
  methods: {
    // 修改用户密码
    // 这里写接口之类的操作
    editUserPassword () {
      const data = {
        id: JSON.parse(localStorage.getItem('userMsg')).id,
        pass: this.resetForm.renewPass
      }
      editUserp(data).then(res => {
        if (res.data.meta.status === 200) {
          this.$message({
            message: res.data.meta.msg,
            type: 'success'
          })
          this.$router.push('/login')
        } else {
          this.$message({
            message: res.data.meta.msg,
            type: 'warning'
          })
        }
      })
    }
  }
}

</script>
<style>
.forPass{
    width: 500px;
    top: 40%;
    text-align: center;
    margin: auto;
}
</style>
